package com.example.demo.controller;

import com.example.demo.dao.entity.Blog;
import com.example.demo.dao.entity.Hospital;
import com.example.demo.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;

    /**
     * 查询博客列表
     * @param model
     * @param blog
     * @return
     */
    @GetMapping("/list")
    public String getBlogList(Model model, Blog blog) {
        List<Blog> list = null;
        if(blog.getTitle() != null && !"".equals(blog.getTitle() )) {
            list = blogService.lambdaQuery()
                    .like(Blog::getTitle,blog.getTitle() )
                    .list();
            model.addAttribute("title", blog.getTitle() );
        }else{
            list = blogService.list();
        }
        model.addAttribute("list", list);
        return "blog/list";
    }

    /**
     * 新增博客页面
     * @param model
     * @param blog
     * @param id
     * @return
     */
    @GetMapping("addpage")
    public String addpage(Model model, @ModelAttribute Blog blog, @RequestParam(value = "id",required = false) Integer id){
        if(!StringUtils.isEmpty(id)){
            Blog byId = blogService.getById(id);
            model.addAttribute("blog",byId);
        }
        return "blog/add";
    }

    @PostMapping(value = {"/add", "/update"}, produces = "application/json")
    public String saveOrUpdate(Model model, Blog blog, Principal principal) {
        String loginName = principal.getName();
        Date now = new Date();
        blog.setCreatePerson(loginName);
        blog.setUpdatePerson(loginName);
        if(blog.getId() == null){
            blog.setCreateTime(now);
        }
        blog.setUpdateTime(now);
        blogService.saveOrUpdate(blog);
        return getBlogList(model,blog);
    }


    /**
     * 删除博客
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public String deleteBlogById( @PathVariable Long id) {
        blogService.removeById(id);
        return "success";
    }
}
